package com.rrx.service;

import com.rrx.mapper.RoleMapper;
import com.rrx.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class RoleService {

    @Autowired
    RoleMapper roleMapper;

    public boolean addRoleAndMenu(int menuId, int roleId) {
        int i = roleMapper.addRoleAndMenu(menuId, roleId);
        if(i > 0)
            return true;
        return false;
    }

    public boolean addRole(String name, String remark) {
        int i = roleMapper.addRole(name, remark);
        if(i > 0)
            return true;
        return false;
    }

    public int getIdByName(String name) {
        Integer id = roleMapper.getIdByName(name);
        if(id == null)
            return -1;
        return id;
    }

    public boolean addRoleAndPermission(int roleId, String permission) {
        if(roleMapper.addRoleAndPermission(roleId, permission) > 0)
            return true;
        return false;
    }

    public int[] getRolesById(int id) {
        int[] i = roleMapper.getRolesById(id);
        return i;
    }

    public String[] getPermissionsById(int id) {
        String[] permissions = roleMapper.getPermissionsById(id);
        return permissions;
    }

    public Role[] getRoleList() {
        return roleMapper.getRoleList();
    }

    public boolean addRoleToAdmin(int adminId, int roleId) {
        int i = roleMapper.addRoleToAdmin(adminId, roleId);
        if(i > 0)
            return true;
        return false;
    }

    public Role[] getAdminRole(int adminId) {
        Role[] roles = roleMapper.getAdminRoles(adminId);
        return roles;
    }


    public boolean updateRole(int roleId, String name, String remark, String[] permissions) {
        if(roleId < 0)
            return false;
        int i = roleMapper.updateRole(name, remark, roleId);
        if(!(i > 0))
            return false;
        if(permissions != null && permissions.length > 0) {
            roleMapper.deleteAllPermission(roleId);
            if(addPermissions(roleId, permissions))
                return true;
            else
                return false;
        }
        return true;
    }
    /**
     * 给角色添加一系列权限
     * @param roleId      角色ID
     * @param permissions 权限节点
     * @return
     */
    private boolean addPermissions(int roleId, String[] permissions) {
        if(permissions != null) {
            for(String s : permissions) {
                int i = roleMapper.addPermission(roleId, s);
                if(i == 0)
                    return false;
            }
        }
        return true;
    }
}
